package com.njlime.core.helper;

import com.alibaba.fastjson.JSONObject;
import com.njlime.core.helper.quartz.QuartzManager;
import com.njlime.core.utils.CronDateUtils;
import com.njlime.sys.entities.RegularTask;
import com.njlime.sys.service.RegularTaskService;
import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class SystemInitialization implements InitializingBean {

    Logger logger = Logger.getLogger(SystemInitialization.class);
    @Resource
    private RegularTaskService regularTaskService;

    public void afterPropertiesSet() throws Exception {
        logger.info("=========================================================");
        logger.info("====================欢迎使用小清柠管理系统==================");
        logger.info("=========================================================");

        try{
            List<RegularTask> regularTaskList = regularTaskService.getJobList();
            for(int i = 0;i< regularTaskList.size(); i++){
                RegularTask regularTask = regularTaskList.get(i);
                logger.info("开始加载定时任务[" + regularTask.getName() + "]");
                JobDataMap jobDataMap = new JobDataMap(JSONObject.parseObject(regularTask.getParam()));
                if(CronDateUtils.getDate(regularTask.getCron()).getTime() > new Date().getTime()){
                    QuartzManager.addJob(regularTask.getName(),Class.forName(regularTask.getClazz()),regularTask.getCron(),jobDataMap);
                }else{
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.SECOND,10);
                    QuartzManager.addJob(regularTask.getName(),Class.forName(regularTask.getClazz()),CronDateUtils.getCron(calendar.getTime()),jobDataMap);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}